package com.tanglongan.designPattern.dp11_flyweight.demo99;

import java.util.HashMap;
import java.util.Map;

public class GenericClient {

    /**
     * 享元抽象
     */
    interface IFlyweight {
        void operation(String extrinsicState);
    }

    /**
     * 具体享元角色
     */
    static class ConcreteFlyweight implements IFlyweight {
        private final String intrinsicState;

        public ConcreteFlyweight(String intrinsicState) {
            this.intrinsicState = intrinsicState;
        }

        @Override
        public void operation(String extrinsicState) {
            System.out.println("Object address:" + System.identityHashCode(this));
            System.out.println("IntrinsicState:" + this.intrinsicState);
            System.out.println("IntrinsicState:" + extrinsicState);
        }
    }

    /**
     * 享元工厂
     */
    static class FlyweightFactory {
        private static final Map<String, IFlyweight> pool = new HashMap<>();

        public IFlyweight getFlyweight(String intrinsicState) {
            if (!pool.containsKey(intrinsicState)) {
                IFlyweight flyweight = new ConcreteFlyweight(intrinsicState);
                pool.put(intrinsicState, flyweight);
            }
            return pool.get(intrinsicState);
        }
    }


    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();
        IFlyweight flyweight1 = factory.getFlyweight("aa");
        IFlyweight flyweight2 = factory.getFlyweight("bb");

        flyweight1.operation("a");
        flyweight2.operation("b");
    }


}
